package com.sqoop.server;

import com.sqoop.core.msg.Msg;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import sun.rmi.runtime.Log;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by - on 2017/11/9.
 */
public class WorkerThread extends Thread {
    private static Logger logger = LogManager.getLogger(WorkerThread.class.getName());

    private BaseProcess baseProcess;
    private String msgId;
    private boolean suspendFlag = false;

   // private static AtomicLong atomicLong =

    public WorkerThread(BaseProcess baseProcess) {
        this.baseProcess = baseProcess;
    }

    @Override
    public void run() {
        while (true) {
            if (suspendFlag) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    continue;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                Msg msg = null;
                try {
                    msg = baseProcess.getMsgBlockingQueue().poll(10, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (msg == null) {
                    continue;
                }
                try {
                    long start = System.currentTimeMillis();
                    baseProcess.process(msg);
                    logger.info("thread {} parse msg used time is {}" ,this.msgId,System.currentTimeMillis()-start);
                    if (!baseProcess.getThreadstatsuccessmap().containsKey(baseProcess.getTaskId())) {
                        baseProcess.getThreadstatsuccessmap().put(baseProcess.getTaskId(), new AtomicLong(0));
                    }
                    baseProcess.getThreadstatsuccessmap().get(baseProcess.getTaskId()).incrementAndGet();
                } catch (Exception e) {
                    e.printStackTrace();
                    if (!baseProcess.getThreadstatfailedmap().containsKey(baseProcess.getTaskId())) {
                        baseProcess.getThreadstatfailedmap().put(baseProcess.getTaskId(), new AtomicLong(0));
                    }
                    baseProcess.getThreadstatfailedmap().get(baseProcess.getTaskId()).incrementAndGet();
                } finally {
                    Thread.yield();
                }
            }
        }
    }


    public void setSuspend(boolean suspendFlag) {
        this.suspendFlag = suspendFlag;
    }

    public String getMsgId() {
        return msgId;
    }

    public void setMsgId(String msgId) {
        this.msgId = msgId;
    }
}